package com.authorize.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class PayUtils {

    /**
     * 签名生成
     * @param params 请求参数
     * @param signKey 签名Key，由创建应用时生成
     * @return
     */
    public static String getSign(String params, String signKey) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String data = signKey+params+signKey;
        return getMd5(data).toLowerCase();
    }
    /**
     * MD5加密方法
     * @param passord
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String getMd5(String passord) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        passord = passord.trim();
        StringBuilder pwd = new StringBuilder("");
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest1 = md.digest(URLEncoder.encode(passord, "UTF-8").getBytes("UTF-8"));
        for (int i = 0; i < digest1.length; i++)
        {
            int v = digest1[i] & 0xFf;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                pwd.append(0);
            }
            pwd.append(hv);
        }
        return pwd.toString();
    }

    /**
     * post 请求
     * @param URL      请求地址
     * @param params   请求参数
     * @param headers  请求头部
     * @return
     */
    public static String doPost(String URL, String params, Map<String,String> headers){
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try{
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("appid",headers.get("appid"));
            if(headers.get("channel") != null){
                conn.setRequestProperty("channel",headers.get("channel"));
            }
            if(headers.get("type") != null){
                conn.setRequestProperty("type",headers.get("type"));
            }
            conn.setRequestProperty("sign",headers.get("sign"));
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            //向post请求发送json数据
            String jsonStr = params;
            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()){
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null){
                    result.append(line);
                    System.out.println(line);
                }
            }else{
                System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }

}
